﻿Imports DevExpress.XtraEditors
Imports System.IO
Imports System.Threading.Tasks

Public Class frmSynchronization

    Private Sub SimpleButtonAdd_Click(sender As Object, e As EventArgs) Handles SimpleButtonAdd.Click
        'frmSynchronization_Form.Dispose()
        frmSynchronization_Form = Nothing
        frmSynchronization_Form.Refresh()
        frmSynchronization_Form.ShowDialog()
    End Sub

    Public Sub loadData(modul As String)
        Dim data As Object
        If modul.Equals("Master") Then
            data = mysql_query("SELECT a.id,b.host,a.database,(SELECT COUNT(*) FROM tb_syncconfig_detail WHERE id_syncconfig=a.id) AS 'total_table' FROM tb_syncconfig AS a INNER JOIN tb_host AS b ON a.id_host=b.id_host")
            'Cek Query Apakah Berjalan?
            If Type.GetTypeCode(data.GetType) <> TypeCode.Boolean Then
                GridControlMaster.DataSource = data
            Else
                'MessageBox.Show("Unable to load Master Configuration")
            End If
            If XtraTabControl1.SelectedTabPageIndex = 0 Then
                If data.Rows.Count > 0 Then
                    SimpleButtonEdit.Enabled = True
                    SimpleButtonDelete.Enabled = True
                    SimpleButtonExport.Enabled = True
                Else
                    SimpleButtonEdit.Enabled = False
                    SimpleButtonDelete.Enabled = False
                    SimpleButtonExport.Enabled = False
                End If
            End If
        Else
            data = mysql_query("SELECT a.id,a.database,b.email,(SELECT COUNT(*) FROM tb_syncconfig_slave_detail WHERE id_syncconfig_slave=a.id) AS 'total_table' FROM tb_syncconfig_slave AS a INNER JOIN tb_contact AS b ON a.id_kontak=b.id_kontak")
            If Type.GetTypeCode(data.GetType) <> TypeCode.Boolean Then
                GridControlSlave.DataSource = data
            Else
                'MessageBox.Show("Unable to load Slave Configuration")
            End If
            If XtraTabControl1.SelectedTabPageIndex = 1 Then
                If data.Rows.Count > 0 Then
                    SimpleButtonEdit.Enabled = True
                    SimpleButtonDelete.Enabled = True
                Else
                    SimpleButtonEdit.Enabled = False
                    SimpleButtonDelete.Enabled = False
                End If
            End If
        End If
    End Sub

    Private Sub frmSynchronization_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        loadData("Master")
        loadData("Slave")
    End Sub

    Private Sub GridViewMaster_CustomUnboundColumnData(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs) Handles GridViewMaster.CustomUnboundColumnData
        If e.Column.AbsoluteIndex = 0 Then
            e.Value = e.ListSourceRowIndex + 1
        End If
    End Sub

    Private Sub GridViewSlave_CustomUnboundColumnData(sender As Object, e As DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs) Handles GridViewSlave.CustomUnboundColumnData
        If e.Column.AbsoluteIndex = 0 Then
            e.Value = e.ListSourceRowIndex + 1
        End If
    End Sub

    Private Sub SimpleButtonDelete_Click(sender As Object, e As EventArgs) Handles SimpleButtonDelete.Click

        Select Case XtraTabControl1.SelectedTabPageIndex
            Case 0
                If XtraMessageBox.Show("Are you sure want to delete this Synchronization Configuration?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    Cursor = Cursors.WaitCursor
                    Dim obj As Object
                    Dim id As String = GridViewMaster.GetFocusedRowCellDisplayText("id").ToString


                    obj = mysql_query(String.Format("SELECT b.host,b.port,b.username,b.password,a.database FROM tb_syncconfig AS a INNER JOIN tb_host AS b ON a.id_host=b.id_host WHERE a.id = '{0}'", id))
                    If Type.GetTypeCode(obj.GetType) <> TypeCode.Boolean Then
                        Dim host_data As DataTable = obj
                        obj = mysql_query(String.Format("SELECT * FROM tb_syncconfig_detail WHERE id_syncconfig = '{0}'", id))
                        If Type.GetTypeCode(obj.GetType) <> TypeCode.Boolean Then
                            Dim data As DataTable = obj
                            For i As Integer = 0 To data.Rows.Count - 1
                                'mysql_non_query("ALTER TABLE " & data.Rows(i)("table_name") & " DROP COLUMN auditlog_timestamp")
                                mysql_non_query("DROP TABLE IF EXISTS auditlog_" & host_data.Rows(0)("database"), False, host_data.Rows(0)("host"), host_data.Rows(0)("port"), host_data.Rows(0)("username"), host_data.Rows(0)("password"), host_data.Rows(0)("database"))
                                mysql_non_query("DROP TRIGGER IF EXISTS insert_auditlog_" & data.Rows(i)("table_name"), False, host_data.Rows(0)("host"), host_data.Rows(0)("port"), host_data.Rows(0)("username"), host_data.Rows(0)("password"), host_data.Rows(0)("database"))
                                mysql_non_query("DROP TRIGGER IF EXISTS update_auditlog_" & data.Rows(i)("table_name"), False, host_data.Rows(0)("host"), host_data.Rows(0)("port"), host_data.Rows(0)("username"), host_data.Rows(0)("password"), host_data.Rows(0)("database"))
                                mysql_non_query("DROP TRIGGER IF EXISTS delete_auditlog_" & data.Rows(i)("table_name"), False, host_data.Rows(0)("host"), host_data.Rows(0)("port"), host_data.Rows(0)("username"), host_data.Rows(0)("password"), host_data.Rows(0)("database"))
                            Next
                            mysql_non_query(String.Format("DELETE FROM tb_syncconfig WHERE id = '{0}'", id))
                            loadData("Master")
                        End If
                    End If

                End If
            Case 1
                If XtraMessageBox.Show("Are you sure want to delete this Synchronization Configuration?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                    Cursor = Cursors.WaitCursor
                    Dim id As String = GridViewSlave.GetFocusedRowCellDisplayText("id").ToString
                    mysql_non_query(String.Format("DELETE FROM tb_syncconfig_slave WHERE id = '{0}'", id))
                    loadData("Slave")
                End If
            Case Else
                Exit Sub
        End Select
        Cursor = Cursors.Default
    End Sub

    Private Sub SimpleButtonRefresh_Click(sender As Object, e As EventArgs) Handles SimpleButtonRefresh.Click
        loadData("Master")
        loadData("Slave")
    End Sub

    Private Sub SimpleButtonExport_Click(sender As Object, e As EventArgs) Handles SimpleButtonExport.Click
        Dim saveFile As New SaveFileDialog()
        Dim sr As StreamReader
        Dim sw As StreamWriter
        Dim RichText As New RichTextBox

        saveFile.Filter = "SQL Dump Files (*.sql)|*.sql"
        saveFile.FilterIndex = 0
        saveFile.RestoreDirectory = True

        If saveFile.ShowDialog() = DialogResult.OK Then
            Dim obj As Object
            Dim mysql As New cMySQLDatabase
            Dim tData As DataTable
            Dim tData2 As DataTable
            'Get Database Name First
            obj = mysql.mysql_query("SELECT a.id_host,b.host,b.port,b.username,b.password,a.database FROM tb_syncconfig AS a INNER JOIN tb_host AS b ON a.id_host=b.id_host WHERE a.id='" & GridViewMaster.GetFocusedRowCellDisplayText("id").ToString & "'")
            If Type.GetTypeCode(obj.GetType) <> TypeCode.Boolean Then
                tData = obj
                If tData.Rows.Count > 0 Then
                    'Copy MySQL Dump Dari Resources
                    Dim entry As System.Reflection.Assembly = System.Reflection.Assembly.GetEntryAssembly
                    Dim fs As Stream = entry.GetManifestResourceStream(String.Format("{0}.{1}", "SyncClient", "mysqldump.exe"))
                    Dim fb(fs.Length) As Byte
                    Dim AppPath As String = Application.StartupPath & "\mysqldump.exe"
                    fs.Read(fb, 0, fb.Length)
                    File.WriteAllBytes(AppPath, fb)
                    fs.Close()
                    Shell(String.Format("{0} --host={1} --port={2} --user={3} --password={4} --databases {5} --ignore-table={5}.auditlog_{5} --skip-triggers --routines --result-file=""{6}""", AppPath, tData.Rows(0)("host"), tData.Rows(0)("port"), tData.Rows(0)("username"), tData.Rows(0)("password"), tData.Rows(0)("database"), saveFile.FileName), AppWinStyle.Hide, True)
                    sr = New StreamReader(saveFile.FileName)
                    RichText.Text = sr.ReadToEnd()
                    sr.Close()
                    RichText.AppendText(vbNewLine & vbNewLine)
                    RichText.AppendText( _
                        "--" & vbCrLf & _
                        "-- Dumping Original Triggers" & vbCrLf & _
                        "--")

                    obj = mysql.mysql_query(String.Format("SHOW TRIGGERS IN {0}", tData.Rows(0)("database")))
                    If Type.GetTypeCode(obj.GetType) <> TypeCode.Boolean Then
                        tData = obj
                        For Each rows As DataRow In tData.Rows
                            If rows("Trigger").ToString.IndexOf("insert_auditlog_") <> 0 And _
                                rows("Trigger").ToString.IndexOf("update_auditlog_") <> 0 And _
                                rows("Trigger").ToString.IndexOf("delete_auditlog_") <> 0 Then
                                obj = mysql.mysql_query(String.Format("SHOW CREATE TRIGGER {0}", rows("Trigger")))
                                If Type.GetTypeCode(obj.GetType) <> TypeCode.Boolean Then
                                    tData2 = obj
                                    RichText.AppendText(tData2.Rows(0)("SQL Original Statement") & vbCrLf)
                                End If
                            End If
                        Next
                    End If

                    'Save Now
                    sw = New StreamWriter(saveFile.FileName)
                    sw.Write(RichText.Text)
                    sw.Close()

                    File.Delete(AppPath)
                    MsgBox("Database Export Done!", MsgBoxStyle.OkOnly, "MySQL Dump")
                End If
            End If
        End If
    End Sub


    Private Sub XtraTabControl1_Click(sender As Object, e As EventArgs) Handles XtraTabControl1.Click
        Console.WriteLine(XtraTabControl1.SelectedTabPageIndex)
        If XtraTabControl1.SelectedTabPageIndex = 0 Then

            If GridViewMaster.RowCount > 0 Then
                SimpleButtonEdit.Enabled = True
                SimpleButtonDelete.Enabled = True
                SimpleButtonExport.Enabled = True
            Else
                SimpleButtonEdit.Enabled = False
                SimpleButtonDelete.Enabled = False
                SimpleButtonExport.Enabled = False
            End If
        Else
            SimpleButtonExport.Enabled = False
            If GridViewSlave.RowCount > 0 Then
                SimpleButtonEdit.Enabled = True
                SimpleButtonDelete.Enabled = True
            Else
                SimpleButtonEdit.Enabled = False
                SimpleButtonDelete.Enabled = False
            End If
        End If
    End Sub
End Class